package com.yzdbx.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.yzdbx.utils.GenUtil;

import java.math.BigDecimal;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.yzdbx.utils.DbUtil.getMaxId;
import static com.yzdbx.utils.GenUtil.CUR_DATE;

/**
 * @BelongsProject: SERVEVICE-DATA-GEN
 * @BelongsPackage: com.yzdbx.task
 * @Author: lk
 * @CreateTime: 2025-05-14
 * @Description: TODO
 * @Version: 1.0
 */
@SuppressWarnings("all")
public class SalefOrderRunnable implements Exe {

    private Connection connection;
    private static final String ALL_CLIENT_SQL = "select id from jcClientInformation";
    private static final String ALL_PRODUCT_SQL = "select id from gy02ProductRepository where productClassification = '产成品'";
    private static final String ALL_USER_SQL = "select memberId as ID from corp_member where memberId != 'admin123'";
    public static final ThreadLocal<List<Integer>> GEN_ORDER_IDS = new ThreadLocal<>();
    private static final int BATCH_SIZE = 100;

    public SalefOrderRunnable(Connection connection) {
        this.connection = connection;
    }

    public boolean execute(int count) {
        System.out.println("传入的count值为：" + count);
        int batchCount = 0;
        List<Integer> genOrderIds = new ArrayList<>(count);
        boolean originalAutoCommit = true;
        
        try {
            // 保存原始自动提交状态
            originalAutoCommit = connection.getAutoCommit();
            connection.setAutoCommit(false);
            
            // 一次性查询所有基础数据
            List<Integer> clientIds = queryClientIds();
            List<Integer> productIds = queryProductIds();
            List<String> userIds = queryUserIds();

            int maxOrderId = getMaxId(connection, "salesOrders");
            int detailMaxId = getMaxId(connection, "xs02SalesOrderBreakdown");

            // 准备批量插入语句
            String detailSql = "insert into xs02SalesOrderBreakdown (id,productInformation,number,associatedSalesOrders,unitPrice,quantityOfShipments,numberOfRemainingShipments,amount) values (?,?,?,?,?,?,?,?)";
            String orderSql = "insert into salesOrders (id,f4ed,clientInformation,dateOfOrder,applicant,numberOfOrders,created,modified,approvalStatus,modifyer,synchronisingFolderFailedSS) values (?,?,?,?,?,?,?,?,?,?,?)";

            try (PreparedStatement detailStatement = connection.prepareStatement(detailSql);
                 PreparedStatement orderStatement = connection.prepareStatement(orderSql)) {

                Date orderDate = Date.valueOf(CUR_DATE.get());
                Timestamp currentTime = GenUtil.CUR_TIME_STAMP.get();

                for (int i = 1; i <= count; i++) {
                    int orderCount = 0;
                    int curOrderId = ++maxOrderId;
                    genOrderIds.add(curOrderId);

                    // 明细产品ID去重且高效
                    int detailCount = RandomUtil.randomInt(1, 4);
                    List<Integer> shuffledProductIds = new ArrayList<>(productIds);
                    Collections.shuffle(shuffledProductIds);

                    for (int j = 0; j < detailCount; j++) {
                        int curDetailId = ++detailMaxId;
                        int productId = shuffledProductIds.get(j);
                        int number = RandomUtil.randomInt(2, 3000);
                        BigDecimal unitPrice = RandomUtil.randomBigDecimal(BigDecimal.ONE, BigDecimal.valueOf(20)).setScale(2, BigDecimal.ROUND_HALF_UP);
                        BigDecimal amount = unitPrice.multiply(BigDecimal.valueOf(number)).setScale(2, BigDecimal.ROUND_HALF_UP);
                        
                        detailStatement.setInt(1, curDetailId);
                        detailStatement.setInt(2, productId);
                        detailStatement.setInt(3, number);
                        detailStatement.setInt(4, curOrderId);
                        detailStatement.setBigDecimal(5, unitPrice);
                        detailStatement.setInt(6, number);
                        detailStatement.setInt(7, 0);
                        detailStatement.setBigDecimal(8, amount);
                        detailStatement.addBatch();
                        
                        orderCount += number;
                    }

                    // 设置订单信息
                    String userId = RandomUtil.randomEle(userIds);
                    orderStatement.setInt(1, curOrderId);
                    orderStatement.setString(2, GenUtil.getNo("XS", i));
                    orderStatement.setInt(3, RandomUtil.randomEle(clientIds));
                    orderStatement.setDate(4, orderDate);
                    orderStatement.setString(5, userId);
                    orderStatement.setInt(6, orderCount);
                    orderStatement.setTimestamp(7, currentTime);
                    orderStatement.setTimestamp(8, currentTime);
                    orderStatement.setString(9, "已通过");
                    orderStatement.setString(10, userId);
                    orderStatement.setString(11, userId);
                    orderStatement.addBatch();

                    batchCount++;
                    
                    // 每BATCH_SIZE条记录执行一次批量插入
                    if (batchCount >= BATCH_SIZE) {
                        detailStatement.executeBatch();
                        orderStatement.executeBatch();
                        connection.commit();
                        batchCount = 0;
                    }
                }

                // 执行剩余的批量插入
                if (batchCount > 0) {
                    detailStatement.executeBatch();
                    orderStatement.executeBatch();
                    connection.commit();
                }
            }

        } catch (Exception e) {
            try {
                if (!connection.getAutoCommit()) {
                    connection.rollback();
                }
            } catch (SQLException ex) {
                throw new RuntimeException("回滚失败", ex);
            }
            throw new RuntimeException("数据生成失败", e);
        } finally {
            try {
                // 恢复原始自动提交状态
                connection.setAutoCommit(originalAutoCommit);
            } catch (SQLException e) {
                throw new RuntimeException("恢复自动提交状态失败", e);
            }
        }

        GEN_ORDER_IDS.set(genOrderIds);
        return Boolean.TRUE;
    }

    /**
     * 查询客户信息
     */
    private List<Integer> queryClientIds() throws SQLException {
        List<Integer> clientIds = new ArrayList<>();
        try (PreparedStatement statement = connection.prepareStatement(ALL_CLIENT_SQL);
             ResultSet resultSet = statement.executeQuery()) {
            while (resultSet.next()) {
                clientIds.add(resultSet.getInt("id"));
            }
        }
        return clientIds;
    }

    /**
     * 查询产品信息
     */
    private List<Integer> queryProductIds() throws SQLException {
        List<Integer> productIds = new ArrayList<>();
        try (PreparedStatement statement = connection.prepareStatement(ALL_PRODUCT_SQL);
             ResultSet resultSet = statement.executeQuery()) {
            while (resultSet.next()) {
                productIds.add(resultSet.getInt("id"));
            }
        }
        return productIds;
    }

    /**
     * 查询用户信息
     */
    private List<String> queryUserIds() throws SQLException {
        List<String> userIds = new ArrayList<>();
        try (PreparedStatement statement = connection.prepareStatement(ALL_USER_SQL);
             ResultSet resultSet = statement.executeQuery()) {
            while (resultSet.next()) {
                userIds.add(resultSet.getString("ID"));
            }
        }
        return userIds;
    }
}
